package com.easemob.helpdesk.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.ashokvarma.bottomnavigation.BadgeItem;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.easemob.helpdesk.EMValueCallBack;
import com.easemob.helpdesk.bean.OwnerInfoRes;
import com.easemob.helpdesk.fragment.AccountFragment;
import com.easemob.helpdesk.fragment.HistorySessionFragment;
import com.easemob.helpdesk.fragment.MsgFragment;
import com.easemob.helpdesk.fragment.OrderFragment;
import com.easemob.helpdesk.fragment.OwnerMsgFragment;
import com.easemob.helpdesk.fragment.OwnerTabMsgFragment;
import com.easemob.helpdesk.fragment.WaitAccessFragment;
import com.easemob.helpdesk.receiver.ServiceOderReceiver;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.PreferenceUtils;
import com.easemob.helpdesk.widget.CustomViewPager;
import com.easemob.helpdesk.widget.pickerview.SimplePickerView;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.easemob.helpdesk.fragment.OwnerFragment;
import com.easemob.helpdesk.fragment.CurrentSessionFragment;
import com.easemob.helpdesk.utils.HDNotifier;
import com.housekeeperapp.activity.BaseActivity;
import com.hyphenate.kefusdk.HDEventListener;
import com.hyphenate.kefusdk.HDNotifierEvent;
//import com.hyphenate.kefusdk.bean.HDSession;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.HDMessage;
//import com.hyphenate.kefusdk.entity.HDUser;
import com.hyphenate.kefusdk.entity.user.HDUser;
import com.hyphenate.kefusdk.manager.session.CloseSessionManager;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.hyphenate.kefusdk.manager.session.OverTimeSessionManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.hyphenate.util.NetUtils;
import com.liyuzhao.badger.BadgeUtil;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;
import com.reactnativenavigation.controllers.NavigationCommandsHandler;
import com.reactnativenavigation.events.Event;
import com.reactnativenavigation.events.JsDevReloadEvent;
import com.reactnativenavigation.params.ActivityParams;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;


public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener {

	private static final String TAG = "MainActivity";

	private ArrayList<Fragment> fragments;
	private CurrentSessionFragment currentSessionFragment;
	private MsgFragment msgFragment;
	private OrderFragment orderFragment;
	private OwnerFragment ownerFragment;
	private AccountFragment accountFragment;
	private OwnerMsgFragment ownerMsgFragment;
	private OwnerTabMsgFragment ownerTabMsgFragment;

	private CustomViewPager mViewPager;

	private RelativeLayout relativeLayout;
	private BottomNavigationBar bottomNavigationBar;
	private HDEventListener eventListener;

	public static MainActivity instance = null;
	public static long userId = 0;
//<<<<<<< HEAD
	public static int userRole = 0;
	public static String mSkillGroup = "";
	public static String easemob_kefu_name;
	public static String easemob_kefu_pwd;
	public static String ticket;
	public static String productKey;
	public static String village;//为空表示此账号为一般的消息中心账号否则表示指挥中心即信息端管家账号
//=======
//	public static String t = "";
//>>>>>>> master-temp

	private BottomNavigationItem chatNavItem;
	private BadgeItem chatNavNumberBadge;

	private long exitTime = 0;

	private List<ActivityParams> activityParams;

//	private ServiceOderReceiver mServiceOderReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		setContentView(R.layout.activity_main);
		instance = this;

		//获取user_id数据
		Intent intent = getIntent();
		mSkillGroup = intent.getStringExtra("skill_group");
		userId = intent.getIntExtra("user_id", 0);
		userRole = intent.getIntExtra("user_role", 0);
		easemob_kefu_name = intent.getStringExtra("easemob_kefu_name");
		easemob_kefu_pwd = intent.getStringExtra("easemob_kefu_pwd");
		ticket = intent.getStringExtra("ticket");
		productKey = intent.getStringExtra("productKey");
		village = intent.getStringExtra("village");

		activityParams = NavigationCommandsHandler.paramsActivityTabs(intent);

		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mViewPager.setOffscreenPageLimit(5);

		bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navbar);
		bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);

		bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
		chatNavNumberBadge = new BadgeItem().setBorderWidth(0).setBackgroundColor(Color.parseColor("#EA5404"));

		BottomNavigationItem contact = new BottomNavigationItem(R.drawable.tab_contact_2,"通讯录").setActiveColor("#EA5404")
				.setInActiveColor("#7B7B7B");
		BottomNavigationItem order = new BottomNavigationItem(R.drawable.tab_more_2,"订单").setActiveColor("#EA5404")
				.setInActiveColor("#7B7B7B");
		BottomNavigationItem account = new BottomNavigationItem(R.drawable.tab_account_2,"账户").setActiveColor("#EA5404")
				.setInActiveColor("#7B7B7B");

		if(userRole == 1){// 消息中心管家
			chatNavItem = new BottomNavigationItem(R.drawable.tab_chat_2,"消息")
					.setActiveColor("#EA5404")
					.setInActiveColor("#7B7B7B")
					.setBadgeItem(chatNavNumberBadge);

			bottomNavigationBar.addItem(chatNavItem)
					.addItem(contact)
					.addItem(order)
					.addItem(account)
					.setFirstSelectedPosition(0)
					.initialise();
			// 发送信息到后台
			HDUser currentUser = HDClient.getInstance().getCurrentUser();
			easemobLoginAfter(currentUser.getUsername(), currentUser.getUserId());

		}else if(userRole == 0){// 物业管家
			chatNavItem = new BottomNavigationItem(R.drawable.tab_chat_2,"消息")
					.setActiveColor("#EA5404")
					.setInActiveColor("#7B7B7B");

			if(!CommonUtils.isBlank(easemob_kefu_name) && !CommonUtils.isBlank(easemob_kefu_pwd)){
				chatNavItem.setBadgeItem(chatNavNumberBadge);
			}

			bottomNavigationBar.addItem(chatNavItem)
					.addItem(contact)
					.addItem(order)
					.addItem(account)
					.setFirstSelectedPosition(0)
					.initialise();
		}else if(userRole == 2){
			bottomNavigationBar
					.addItem(order)
					.addItem(account)
					.setFirstSelectedPosition(0)
					.initialise();
		}

		fragments = getFragments();
		bottomNavigationBar.setTabSelectedListener(this);

		mViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				bottomNavigationBar.selectTab(position);
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
		//会话消息监听
		registerMessageListener();

		//注册广播
//		mServiceOderReceiver = new ServiceOderReceiver();
//		IntentFilter intentFilter = new IntentFilter();
//		intentFilter.addAction("com.housekeeperapp.serviceorder");
//		registerReceiver(mServiceOderReceiver, intentFilter);
	}

	public ActivityParams getCurActParams(int index){
		return activityParams.get(index);
	}

	private void registerMessageListener() {
		if (eventListener == null){
			eventListener = new HDEventListener() {
				@Override
				public void onEvent(final HDNotifierEvent event) {

					Log.d(TAG, "registerMessageListener===onEvent: "+Thread.currentThread());
					final Object data = event.getData();
					runOnUiThread(new Runnable() {
						@Override
						public void run() {

							switch (event.getEvent()){
								case EventNewMessage:
									if (data instanceof HDMessage){
										HDMessage HDMessage = (com.hyphenate.kefusdk.entity.HDMessage) data;
										if (!HDMessage.isAgentChat()){
											if (CurrentSessionFragment.refreshCallback != null) {
												CurrentSessionFragment.refreshCallback.onRefreshView();
												HDNotifier.getInstance().notifiChatMsg(HDMessage);
											}
										}
									}
									break;

								case EventNewSession:
									if (CurrentSessionFragment.callback != null) {
										HDNotifier.getInstance().notifiChatMsg(null);
										CurrentSessionFragment.callback.onFresh(null);
									}
									break;
								case EventVisitorWaitListChange:
									if (TextUtils.isEmpty(village)){
//									if ((userId < 217 || (userId > 230 && userId < 245) || userId > 248)) {
										if (WaitAccessFragment.callback != null) {
											WaitAccessFragment.callback.onFresh(new EMValueCallBack() {
												@Override
												public void onSuccess(Object value) {
													int curInt = Integer.parseInt(value.toString());

													if (PreferenceUtils.getInstance().getNotiWaitCount() < curInt) {
														HDNotifier.getInstance().notifiChatMsg(null);
													}

													PreferenceUtils.getInstance().setNotiWaitCount(curInt);
												}

												@Override
												public void onError(int error, String errorMsg) {

												}
											});
										}
									}else {//信息端管家不通知消息

									}

									break;
								case EventCurrentUserDelete:
//									tipCurrentUserDeleted();
									break;
								case EventSessionClosed:
									OverTimeSessionManager.getInstance().notifyListeners((String) data);
									if(HistorySessionFragment.callback != null){
										HistorySessionFragment.callback.onFresh(null);
									}
									break;
								case EventMaxSessionsChanged:
//									refreshMaxAccessCount();
									break;
								case EventSessionClosedByAdmin:
									if (data instanceof List){
										List<JSONObject> jsonList = (List<JSONObject>) data;
										if(jsonList != null && !jsonList.isEmpty()){
											for (JSONObject jsonObject : jsonList) {
												try {
													String strBody = jsonObject.getString("body");
													String sSessionId = strBody.substring(0, strBody.indexOf(":"));
													if (sSessionId != null) {
														CloseSessionManager.getInstance().notifyListeners(sSessionId);
													}
												} catch (Exception e) {
													e.printStackTrace();
													HDLog.e(TAG, "ServiceSessionClosedByAdmin error:" + e.getMessage());
												}
											}
										}

									}

									break;
								case EventSessionTransfered:
									if (data instanceof List){
										List<JSONObject> jsonList = (List<JSONObject>) data;
										if (jsonList != null && !jsonList.isEmpty()){
											for (JSONObject jsonObject : jsonList) {
												try {
													String strBody = jsonObject.getString("body");
													String [] splitStr = strBody.split(":");
													String sSessionId = splitStr[1];
													if (sSessionId != null) {
														CloseSessionManager.getInstance().notifyListeners(sSessionId);
													}
												} catch (Exception e) {
													e.printStackTrace();
													HDLog.e(TAG, "ServiceSessionTransfered error:" + e.getMessage());
												}
											}
										}
									}
									break;
							}

						}
					});

				}
			};
		}
		HDClient.getInstance().chatManager().addEventListener(eventListener);
	}

	private void easemobLoginAfter(String easemob_kefu_name, String easemob_kefu_id){

		ApiService apiService = HKHttpUtils.getApiService();
		Call<BaseResponse> call = apiService.updateUserId(ticket, easemob_kefu_name, easemob_kefu_id);
		call.enqueue(new HKResponseResultCallBack<Object>() {
			@Override
			public void onSuccess(Object o) {

			}

			@Override
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(MainActivity.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFailed(Call call, Throwable t) {
				Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
			}
		});
	}

	private ArrayList<Fragment> getFragments() {
		ArrayList<Fragment> fragments = new ArrayList<>();

		if (orderFragment == null){
			orderFragment = new OrderFragment();
		}

		if(accountFragment == null){
			accountFragment = new AccountFragment();
		}

		if(userRole == 1){//管家中心
			if(msgFragment == null){
				msgFragment = new MsgFragment();
			}

			fragments.add(msgFragment);
		}

		if(userRole == 0){//物业管家
			if(CommonUtils.isBlank(easemob_kefu_name) || CommonUtils.isBlank(easemob_kefu_pwd)){
				if(ownerMsgFragment == null){
					ownerMsgFragment = new OwnerMsgFragment();
				}

				fragments.add(ownerMsgFragment);
			}else{
				if(ownerTabMsgFragment == null){
					ownerTabMsgFragment = new OwnerTabMsgFragment();
				}

				fragments.add(ownerTabMsgFragment);
			}

		}

		if(userRole == 0 || userRole == 1){
			if (ownerFragment == null){
				ownerFragment = new OwnerFragment();
			}

			fragments.add(ownerFragment);
		}

		fragments.add(orderFragment);
		fragments.add(accountFragment);

		return fragments;
	}


	@Override
	public void onTabSelected(int position) {
//		if(position == 2){
////			if(NavigationActivity.currentActivity == null){
////
////				MainApplication app = (MainApplication)getApplication();
////				app.getEventEmitter().sendEvent("startJsView");
////
////				bottomNavigationBar.selectTab(0);
////			}else{
////				NavigationActivity.currentActivity.setVisible(true);
////			}
//
//
//		}else{
////			mViewPager.setCurrentItem(position);
//		}

		mViewPager.setCurrentItem(position);
	}

	@Override
	public void onTabUnselected(int position) {

	}

	@Override
	public void onTabReselected(int position) {

	}

	public void refreshSessionUnreadCount(int waitCount) {
		int unReadCount = CurrentSessionManager.getInstance().getTotalUnReadCount();
//		int waitCount = msgFragment.getWaitTotalCount();
		if(msgFragment != null){
			msgFragment.refreshCurUnreadCount();
		}

		if(ownerTabMsgFragment != null){
			ownerTabMsgFragment.refreshCurUnreadCount();
		}

		if ((unReadCount+waitCount) > 0) {
			if (unReadCount+waitCount > 99) {
				chatNavNumberBadge.setText("99+");
			} else {
				chatNavNumberBadge.setText(String.valueOf(unReadCount+waitCount));
			}
			chatNavNumberBadge.show();
			// 设置角标数量
			BadgeUtil.setBadgeCount(this, (unReadCount+waitCount));
		} else {
			chatNavNumberBadge.hide();
			BadgeUtil.resetBadgeCount(this);
		}
	}

	/**
	 * 信息端
	 * @param currentCount
	 * @param isInfomationClient
	 */
	public void refreshSessionUnreadCount(int currentCount,boolean isInfomationClient){
		if (isInfomationClient){//是信息端
			if ((currentCount) > 0) {
				if (currentCount > 99) {
					chatNavNumberBadge.setText("99+");
				} else {
					chatNavNumberBadge.setText(String.valueOf(currentCount));
				}
				chatNavNumberBadge.show();
				// 设置角标数量
				BadgeUtil.setBadgeCount(this, (currentCount));
			} else {
				chatNavNumberBadge.hide();
				BadgeUtil.resetBadgeCount(this);
			}
		}else {//非信息端
			refreshSessionUnreadCount(currentCount);
		}
	}

	public MsgFragment getMsgFragment(){
		return msgFragment;
	}

	@Override
	protected void onResume() {
		super.onResume();
		//View出现时
		MainApplication.getInstance().getEventEmitter().sendNavigatorEvent("willAppear", activityParams.get(1).screenParams.getNavigatorEventId());
		MainApplication.getInstance().getEventEmitter().sendNavigatorEvent("didAppear", activityParams.get(1).screenParams.getNavigatorEventId());

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 清除数据
		MainApplication.getInstance().getEventEmitter().sendEvent("clearData");
		instance = null;
		if (eventListener != null){
			HDClient.getInstance().chatManager().removeEventListener(eventListener);
		}

//		unregisterReceiver(mServiceOderReceiver);

		if(MainApplication.getInstance().loadingDialog != null){
			MainApplication.getInstance().loadingDialog.dismiss();
		}

	}

	@Override
	public void onEvent(Event event) {
		super.onEvent(event);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);


	}

	private class MyPagerAdapter extends FragmentPagerAdapter {
		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return fragments.get(position);
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void exit() {
//		if ((System.currentTimeMillis() - exitTime) > 2000) {
//			Toast.makeText(getApplicationContext(), "再按一次退出程序",
//					Toast.LENGTH_SHORT).show();
//			exitTime = System.currentTimeMillis();
//		} else {
//			((MainApplication) getApplication()).exitApp();
//		}

//<<<<<<< HEAD
		moveTaskToBack(true);
//=======
//			moveTaskToBack(true);
//>>>>>>> master-temp
	}

	public void selectTab(int index){
		bottomNavigationBar.selectTab(index);
	}

}
